package com.shujia.wyh.java_moni_hadoop;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class Reduce {
    public static void main(String[] args) throws Exception {
        //创建一个Map集合统计每个班级的人数
        HashMap<String, Integer> map = new HashMap<>();

        //将mapouts目录封装成File对象
        File file = new File("bigdata23-hadoop/data/mapouts");
        File[] files = file.listFiles();
        BufferedReader br = null;
        if(files!=null){
            for (File file1 : files) {
                br = new BufferedReader(new FileReader(file1.getAbsolutePath()));
                String line = null;
                while ((line = br.readLine()) != null) {
                    String clazz = line.split(":")[0];
                    Integer number = Integer.valueOf(line.split(":")[1]);
                    if (!map.containsKey(clazz)) {
                        map.put(clazz, number);
                    } else {
                        map.put(clazz, number + map.get(clazz));
                    }
                }
            }
        }


        //创建一个字符缓冲输出流对象
        BufferedWriter bw = new BufferedWriter(new FileWriter("bigdata23-hadoop/data/output/part-r-00000"));

        //遍历集合写入到最终结果文件
        Set<Map.Entry<String, Integer>> entries = map.entrySet();
        for (Map.Entry<String, Integer> entry : entries) {
            String clazz = entry.getKey();
            Integer numbers = entry.getValue();
            bw.write(clazz + "\t" + numbers);
            bw.newLine();
            bw.flush();
        }

        //释放资源
        bw.close();
        if (br != null) {
            br.close();
        }

    }
}
